package com.abxh.jetpack.base

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.lifecycle.ViewModelProvider
import com.abxh.jetpack.IViewModel
import com.abxh.jetpack.LazyFragment
import java.lang.reflect.ParameterizedType

/**
 * Created by dab on 2021/8/10 14:54
 */
open abstract class BaseViewModelFragment<VM : IViewModel> : LazyFragment() {
    lateinit var viewModel: VM
    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        /*利用反射获取类实例*/
        val persistentClass =
            (javaClass.genericSuperclass as ParameterizedType).actualTypeArguments[0] as Class<VM>
        viewModel = ViewModelProvider(
            this,
            ViewModelProvider.AndroidViewModelFactory.getInstance(activity!!.application)
        ).get(persistentClass)
        return super.onCreateView(inflater, container, savedInstanceState)
    }


}
